package com.study.controller;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLException;

@RestController
@ControllerAdvice
public class MyController {

    private void randomException() throws Exception {
        Exception[] exceptions = {
                new NullPointerException(),
                new ArrayIndexOutOfBoundsException(),
                new ClassNotFoundException(),
                new SQLException(),
                new NumberFormatException()
        };

        //发生概率
        double probability = 0.75;

        double num = Math.random();
        if(num < probability) {
            System.out.println("当前概率为： " + num +","+ "将会触发异常");
            throw exceptions[(int) (num * exceptions.length)];
        }
    }

    @RequestMapping("/index")
    public String index() throws Exception {
        randomException();
        return "success";
    }

    @RequestMapping("/test")
    public String test() {
        int i = 1 / 0;
        return "test";
    }
}
